package juc.juccore.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * 演示原子数组的使用方法
 */
public class AtomicArrayDemo {
    public static void main(String[] args) {
        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000);
        Incrementer incrementer = new Incrementer(atomicIntegerArray);
        Decrementer decrementer = new Decrementer(atomicIntegerArray);
        Thread[] threadIncrementer = new Thread[100];
        Thread[] threadDecrementer = new Thread[100];
        for (int i = 0; i < 100; i++) {
            threadDecrementer[i] = new Thread(decrementer);
            threadIncrementer[i] = new Thread(incrementer);
            threadDecrementer[i].start();
            threadIncrementer[i].start();
        }
        for (int i = 0; i < 100; i++) {
            try {
                threadDecrementer[i].join();
                threadIncrementer[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            if (atomicIntegerArray.get(i) != 0) {
                System.out.println("发现了错误" + i);
            }
        }
        System.out.println("运行结束");

    }
}

class Incrementer implements Runnable {
    private AtomicIntegerArray atomicIntegerArray;

    public Incrementer(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndIncrement(i);
        }
    }
}

class Decrementer implements Runnable {
    private AtomicIntegerArray atomicIntegerArray;

    public Decrementer(AtomicIntegerArray atomicIntegerArray) {
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndDecrement(i);
        }
    }
}